<template>
  <view>
    <Header type="back" title="提交订单" />
    <view
      class="bg-f8ff py-2 w-100 px-2-6 ab left0 bottom0 rounded-right ov-hd-y"
      :class="'top' + toprpx"
    >
      <view class="w-100 py-3 px-2-4 font32 t-20">商品详情</view>
      <!-- <view class="w-100 h1 bg-ccc"></view> -->
      <view class="w-100 px-2-4 pb-3">
        <view class="ov-hd pb-2" :class="set_height">
          <view
            class="w-100 mt-3"
            v-for="(item, index) in order_ticket_car"
            :key="item.id"
          >
            <view class="f-y-s">
              <ImageFile :url="item.thumbnail" className="w142 h142 circle12" />
              <view class="fs-b-b pl-3 w530 h142">
                <view class="w-100 font700 mt-1 font25 t-20">{{
                  item.name
                }}</view>
                <view class="w-100 f-b-c font25 t-20">
                  <view class="font25 t-20">购买数量 x {{ item.number }}</view>
                  <view class="">
                    <text class="font20 t-20">¥</text>
                    <text class="font700 font25 t-20">{{
                      (item.number * item.price).toFixed(2)
                    }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view
          class="f-c-c py-2"
          v-if="order_ticket_car.length > 2"
          @click="set_food_show"
        >
          <text class="font22 t-8 font400"
            >{{ food_show ? "收起" : "展开" }}更多</text
          >
          <image
            src="../../static/icon_right.png"
            :class="food_show ? 'ty-all-down' : 'ty-all'"
            class="w22 h22 re ml-1"
          />
        </view>
      </view>

      <!-- <Recommend :goodsType="goods_type" @get_recommend="set_recommend" /> -->

      <view class="w-100 px-2-4 pt-3">
        <!-- <view class="w-100 font28 t-20 font500 mb-5">商品小计</view> -->
        <!-- <view class="w-100 f-b-c mb-5 h24">
					<view class="font25 font400 t-20">积分抵扣：<text class="t-ed mx-06">-￥10.0</text>（消耗9000积分）</view>
					<view class="" @click="set_deduction">
						<image src="../../static/icon_select.png" class="w34 h34" v-show="!deduction"/>
						<image src="../../static/icon_select_cur.png" class="w34 h34" v-show="deduction"/>
					</view>
				</view> -->
        <!-- <view class="w-100 f-b-c mb-5 h24">
          <view class="font25 font400 t-20"
            >优惠券：
            <text class="t-ed mx-06" v-if="order_coupon.id"
              >-￥{{ order_coupon.money }}</text
            ></view
          >

          <view
            class="font25 t-0 f-y-c font600"
            @click="change_coupon()"
            v-if="order_coupon.id"
            >已选择
            <image src="../../static/icon_right_0.png" class="w24 h24" />
          </view>
          <view class="font25 t-3 f-y-c" v-else> 暂无可用优惠券 </view>
        </view> -->
      </view>

      <view class="w-100 h1 bg-ccc"></view>

      <view class="w-100 f-b-c h24 px-2-4 py-3">
        <view></view>
        <view class="font28 t-0 font700"
          ><text class="mx-06 pr-1 font400 font22">合计</text>￥{{
            order_info.money
          }}</view
        >
      </view>
      <view class="w-100 h273"></view>
    </view>
    <view class="w-100 fixed bottom0 pb-5 left0 z-999 option">
      <view class="w-100 px-4">
        <view class="w-100 f-b-c bg-theme_3 h100 circle120 pl-5">
          <view class="pl-1 font28 font700 t-w f-y-c">
            <text class="font24 font400 mr-05">合计</text>¥{{
              order_info.money
            }}
            <!-- <text class="font21 t-theme font500 mx-06 pl-1"
              >已优惠￥{{ order_info.coupon }}</text
            > -->
          </view>
          <view
            class="w220 h100 f-c-c bg-theme circle120 font28 font700 t-20"
            @click="get_purchass"
            >去支付</view
          >
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState, mapActions } from "vuex";
import Header from "../../components/header.vue";
import ImageFile from "../../components/img_file.vue";
import Recommend from "../../components/recommend.vue";

import { order_submit } from "../../api/order.js";

import weixin_pay from "../../common/weixinPay.js";
import time from "../../common/time.js";

export default {
  components: {
    Header,
    ImageFile,
    Recommend,
  },
  mixins: [weixin_pay, time],
  data() {
    return {
      toprpx: 0,
      food_show: false,
      deduction: false, //积分抵扣
      order_info: {},
      order_food_number: 0,
      order_food_money: 0,
      order_ticket_car: [],
      goods_type: ["TICKET"], // TICKET,ACTIVITY,YEAR_CARD,MALL,FOOD,MAP,LINE,COUPON
      goods_order: [],
    };
  },
  watch: {
    "order_coupon.id": {
      handler() {
        this.set_order_info();
      },
    },
    "order_coupon.money": {
      handler() {
        this.set_order_info();
      },
    },
  },
  onShow() {
    this.order_coupon = uni.getStorageSync("change_coupon") || {};
  },
  created() {
    this.purchase_type = uni.getStorageSync("purchase_type");
    this.order_ticket_car = [uni.getStorageSync("createdOrder")];
    this.get_my_coupon(this.purchase_type, this.order_ticket_car);
    this.goods_type = [this.purchase_type];
    this.set_order_info();
    this.set_order();
  },
  mounted() {
    this.toprpx = uni.getStorageSync("toprpx");
  },
  onUnload() {
    uni.setStorageSync("change_coupon", {});
  },
  methods: {
    set_order() {
      let price = 0;
      let number = 0;
      let other_p = 0;
      let other_n = 0;
      this.order_ticket_car.forEach((item) => {
        let type = item.goodsType || item.type;
        if (this.purchase_type == type) {
          price += item.price * item.number;
          number += item.number;
        } else {
          other_p += item.price * item.number;
          other_n += item.number;
        }
      });
      this.order_food_money =
        parseFloat(price.toFixed(2)) + parseFloat(other_n.toFixed(2));
      this.order_food_number = number + other_n;
      // this.order_ticket_car = JSON.parse(JSON.stringify(this.food_car))
      this.$forceUpdate();
    },
    // 计算合计
    set_order_info() {
      let coupon = this.order_coupon?.money || 0;
      let goods_info = this.get_ticket_info();

      let money = 0,
        coupon_state = false;
      if (goods_info.money * 1 < coupon * 1) {
        money = "0.00";
        coupon_state = true;
      } else {
        money = (goods_info.money * 1 - coupon * 1).toFixed(2);
      }
      this.order_info = {
        money: (parseFloat(money) + goods_info.other_m).toFixed(2), // 后续需要加上 积分抵扣
        coupon: coupon_state ? goods_info.money : (0 + coupon * 1).toFixed(2), // 后续需要加上 积分抵扣
      };

      if (coupon_state) {
        this.order_coupon.money = goods_info.money;
      }
    },
    // 获取直购订单数据
    get_ticket_info() {
      let number = 0,
        money = 0,
        other_n = 0,
        other_m = 0;
      this.order_ticket_car?.forEach((item) => {
        let type = item.goodsType || item.type;
        if (this.purchase_type == type) {
          number += item.number;
          money += item.number * item.price;
        } else {
          other_n += item.number;
          other_m += item.number * item.price;
        }
      });
      this.order_food_money = parseFloat(money.toFixed(2));
      return { number, money, other_n, other_m };
    },
    set_food_show() {
      this.food_show = !this.food_show;
    },
    set_deduction() {
      this.deduction = !this.deduction;
    },
    change_coupon() {
      // 在weixinPay.js中默认选择优惠券时 存了当前选择的优惠券
      // 需要把当前价格传过去 进行筛选
      uni.navigateTo({
        url: `/pages/purchase/change_coupon?type=${this.purchase_type}&money=${
          this.order_food_money
        }&goods=${JSON.stringify(this.order_ticket_car)}`,
      });
    },
    // 设置添加 加购商品
    set_recommend(val) {
      let obj = this.order_ticket_car.find((item) => item.id == val.id) || {};
      if (val.state) {
        if (!obj.id) {
          this.order_ticket_car.push(val);
        } else {
          this.order_ticket_car.find((item) => {
            if (item.id == val.id) {
              item.number++;
            }
          });
        }
      } else {
        if (obj.number > 1) {
          this.order_ticket_car.find((item) => {
            if (item.id == val.id) {
              item.number--;
            }
          });
        } else {
          let index = this.order_ticket_car.findIndex(
            (item) => item.id == val.id
          );
          this.order_ticket_car.splice(index, 1);
        }
      }

      // 是否存在加购订单且不是同类商品
      this.set_order();
      // 计算提交订单的数据
      this.set_order_info();
      // 加购完成需要更新优惠券
      this.get_my_coupon(this.purchase_type, this.order_ticket_car);
    },
    // 设置订单信息
    set_goods_list(array) {
      const list = [],
        list_1 = [];
      let totalFee = 0;
      let totalNum = 0;
      let coupon_fee = 0;
      let coupon_num = 0;
      array?.forEach((item) => {
        let time = "";
        if (this.goods_type.includes("TICKET")) {
          time = item.orderDate;
        }

        let activityPlanId = ["ACTIVITY", "WORKSHOP"].includes(
          this.purchase_type
        )
          ? item.addressId
          : "";

        let lineItemType = ["LINE"].includes(this.purchase_type)
          ? item.lineItemType
          : "";

        let type = item.goodsType || item.type;
        if (this.purchase_type == type) {
          list.push({
            // activityPlanId, // 活动排班id 排班订单不能为空
            date: time, //预约日期 票务订单不能为空
            // lineItemType, //路线类型 1：材料包/2：导览服务
            goodsId: item.id,
            goodsName: item.name,
            number: item.number,
            orderType: this.goods_type.toString(),
            totalFee: item.number * item.price,
            unitFee: item.price,
          });
          totalFee += parseFloat((item.number * item.price).toFixed(2));
          totalNum += item.number;
        } else {
          list_1.push({
            activityPlanId: "", // 活动排班id 排班订单不能为空
            date: "", //预约日期 票务订单不能为空
            lineItemType: "", //路线类型 1：材料包/2：导览服务
            goodsId: item.id,
            goodsName: item.name,
            number: item.number,
            totalFee: item.number * item.price,
            unitFee: item.price,
          });
          coupon_fee += parseFloat((item.number * item.price).toFixed(2));
          coupon_num += item.number;
        }
      });
      return { list, list_1, totalFee, totalNum, coupon_fee, coupon_num };
    },
    async get_purchass() {
      const userInfo = uni.getStorageSync("userInfo") || {};
      const orgId = uni.getStorageSync("orgId") || "";

      let food = this.set_goods_list(this.order_ticket_car);

      console.log("this.order_info.money", this.order_info.money);
      console.log("order_coupon", this.order_coupon.money);
      console.log("food", food);
      let order_info_money = this.order_info.money || 0;
      let data = {
        orgId: orgId,
        storeId: uni.getStorageSync("storeId") || "",
        goodsFee: order_info_money, // 商品总金额
        payFee: order_info_money, // 支付金额
        receivableFee: order_info_money, // 应收金额
        memberId: userInfo.id,
        remark: "",
        goodsDTOList: food.list,
        // 渠道
        clientType: 'MINI',
        // 支付方式
        payMethod: 'WX'
      };

      // if (food.list_1.length) {
      //   data.subOrderList[1] = {
      //     addressId: "",
      //     couponFee: "",
      //     couponId: "",
      //     freightFee: 0, //运费
      //     goodsList: food.list_1,
      //     payFee: food.coupon_fee.toFixed(2),
      //     orderType: "COUPON", //food FOOD,TICKET,YEAR_CARD,MALL,MAP ,LINE
      //     tableNo: "", // 桌号
      //     totalFee: food.coupon_fee,
      //     totalNum: food.coupon_num,
      //   };
      // }

      // 是否存在加购订单且不是同类商品 且已加购商品
      // if(this.goods_order.length){
      // 	let array = [],arr = [],list = {}
      // 	this.goods_type.map(item=>{
      // 		array = []
      // 		list = {}
      // 		this.goods_order.map(obj=>{
      // 			if(item === obj.goodsType){
      // 				array.push(obj)
      // 			}
      // 		})
      // 		list.list = array
      // 		list.type = item
      // 		arr.push(list)
      // 	})
      // 	console.log('sss',arr)
      // 	arr.map(goods=>{
      // 		let goods_type = this.set_goods_list(goods.list)
      // 		let goods_info = {
      // 			"addressId": '',
      // 			"couponFee": '',
      // 			"couponId": "",
      // 			"freightFee": 0, //运费
      // 			"goodsList": goods_type.list,
      // 			"orderType": goods.type, //food FOOD,TICKET,YEAR_CARD,MALL,MAP ,LINE
      // 			"tableNo": "", // 桌号
      // 			"sendType": 0, // 寄送方式 1：自提/2：邮寄
      // 			"payFee": goods_type.totalFee,
      // 			"totalFee": goods_type.totalFee,
      // 			"totalNum": goods_type.totalNum,
      // 			}
      // 		data.subOrderList.push(goods_info)
      // 	})
      // }
      // let money = 0;
      // data.subOrderList?.map((item) => {
      //   money += parseFloat(item.payFee);
      // });
      // data.payFee = money.toFixed(2);
      // data.subOrderList.forEach((v) => {
      //   v.totalFee = v.totalFee.toFixed(2);
      // });
      const { code, body } = await order_submit(data);
      if (code === "0") {
        // 去提交支付
        this.get_wx_order(body, this.purchase_type);
        uni.setStorageSync("order_code", this.purchase_type);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.radius-32-botton {
  border-radius: 32rpx 32rpx 0 32rpx;
}
.radius-32-right {
  border-radius: 0 32rpx 0 0;
  .ty-li {
    border-top: 1rpx solid #ccc;
    &:first-child {
      border-top: none;
    }
  }
}
.t-del {
  &::after {
    content: "";
    width: 100%;
    height: 1rpx;
    background: #8a8a8a;
    position: absolute;
    top: 50%;
    left: 0;
  }
}
.ty-all {
  transform: rotate(90deg);
  transition: all 0.3s;
}
.ty-all-down {
  transform: rotate(270deg);
  transition: all 0.3s;
}
.hauto {
  height: auto !important;
  transition: all 0.3s;
}
</style>
